package com.base.myproject.client.HR.recruitment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.BaseTabPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Label;

/**
 * @author cxghiu4102@gmail.com 安排初试
 * 
 */
public class PositionRequestSearch extends BaseJDBCPanel {
	BaseStore<BusiObject> store;
	PagingToolBar toolBar1 = null;

	Button fuzzy_search = new Button("模糊查询");// 查询按钮
	Button precise_search = new Button("精确查询");// 查询按钮
	Button interview = new Button("安排面试"); // 面试按钮

	String sql = "select * from hr_positionRequest where 1=2";

	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>(
			"id",
			"name",
			"SystemInfo",
			"where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",
			true);

	public PositionRequestSearch() {
		init();
	}

	public void init() {
		initWeigetx();
		registerMainStore(resultStore);
		fuzzy_search.addListener(Events.OnClick, getListener());
		precise_search.addListener(Events.OnClick, getListener());
		interview.addListener(Events.OnClick, getListener());
	}

	private void initWeigetx() {
		toolBar1 = new PagingToolBar(15);

		BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH,
				150);
		southData.setCollapsible(true);
		southData.setFloatable(true);
		southData.setSplit(true);
		southData.setMargins(new Margins(0, 5, 0, 5));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 5, 5));

		VerticalPanel vp = new VerticalPanel();
		vp.setSpacing(5);

		vp.add(createForm());
		HorizontalPanel s = new HorizontalPanel();
		s.add(fuzzy_search);
		s.add(precise_search);
		s.add(interview);
		vp.add(s);

		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.add(this.createGrid());
		panel2.setBottomComponent(toolBar1);
		vp.add(panel2);

		ContentPanel content = new ContentPanel();
		content.setScrollMode(Scroll.AUTO);
		content.setHeaderVisible(false);
		content.add(vp);

		ContentPanel south = new ContentPanel();
		south.setHeading("面试结果填写");
		south.add(createResultForm());

		add(content, centerData);
		add(south, southData);
	}

	BaseStore<BusiObject> resultStore = null;

	BaseStore<BusiObject> getResultStore() {
		if (resultStore == null) {
			createResultStore();
		}
		return resultStore;
	}

	BaseStore<BusiObject> createResultStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("recruitmentId");
		type.getField("recruitmentId").setType(Integer.class);
		type.addField("resumeLibraryId");
		type.getField("resumeLibraryId").setType(Integer.class);
		type.addField("requestDate");
		type.getField("requestDate").setType(Date.class);
		type.addField("situation");
		type.getField("situation").setType(String.class);
		type.addField("informationForm");
		type.getField("informationForm").setType(String.class);
		type.addField("reason");
		type.getField("reason").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_positionRequest");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_positionRequest where icode = {icode}");
		info.setParent(store);
		info.setLinkparentcolumns(new String[] { "icode" });
		info.setLinkparent_chile_columns(new String[] { "icode" });
		resultStore = new BaseStore<BusiObject>(type, info);
		return resultStore;
	}

	BaseFormPanel createResultForm() {
		BaseFormPanel form = new BaseFormPanel(getResultStore());
		TableLayout tl = new TableLayout(6);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label("面试情况:"), td);
		BaseComboBoxX box = new BaseComboBoxX("name", "dictionary",
				"where type='interview'");
		box.setName("situation");
		form.add(box, td);
		form.add(new Label("信息来源:"), td);
		BaseComboBoxX box1 = new BaseComboBoxX("name", "dictionary",
				"where type='informationFrom'");
		box1.setName("informationForm");
		form.add(box1, td);
		form.add(new Label("不适合原因:"), td);
		BaseComboBoxX box2 = new BaseComboBoxX("name", "dictionary",
				"where type='reason'");
		box2.setName("reason");
		form.add(box2, td);
		form.setBodyBorder(false);

		form.inited();
		return form;
	};

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("requestNo");
		type.getField("requestNo").setType(String.class);
		type.addField("depCode");
		type.getField("depCode").setType(String.class);
		type.addField("position");
		type.getField("position").setType(String.class);
		type.addField("grade");
		type.getField("grade").setType(String.class);
		type.addField("education");
		type.getField("education").setType(String.class);
		type.addField("experience");
		type.getField("experience").setType(String.class);
		type.addField("skills");
		type.getField("skills").setType(String.class);

		type.addField("resumeNo");
		type.getField("resumeNo").setType(String.class);
		type.addField("name");
		type.getField("name").setType(String.class);
		type.addField("bEducation");
		type.getField("bEducation").setType(String.class);
		type.addField("bExperience");
		type.getField("bExperience").setType(String.class);
		type.addField("salary");
		type.getField("salary").setType(Double.class);
		type.addField("bSkills");
		type.getField("bSkills").setType(String.class);
		type.addField("uploadFile");
		type.getField("uploadFile").setType(String.class);
		type.addField("uploadFileName");
		type.getField("uploadFileName").setType(String.class);
		type.addField("requestDate");
		type.getField("requestDate").setType(Date.class);
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("situation");
		type.getField("situation").setType(String.class);
		type.addField("informationForm");
		type.getField("informationForm").setType(String.class);
		type.addField("reason");
		type.getField("reason").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_positionRequest");
		info.setKeyname(new String[] { "icode" });
		info.setSql(sql);
		store = new BaseStore<BusiObject>(type, info);
		store.setToolBar(toolBar1);
		return store;
	}

	BaseGrid<BusiObject> grid = null;
	CheckBoxSelectionModel<BusiObject> cbs;

	BaseGrid<BusiObject> createGrid() {
		cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C30 = new ColumnConfig("requestNo", "职位编号", 80);
		columns.add(C30);
		ColumnConfig C2 = new ColumnConfig("depCode", "职位部门", 80);
		columns.add(C2);

		ColumnConfig C4 = new ColumnConfig("position", "职位名称", 80);
		columns.add(C4);

		ColumnConfig C6 = new ColumnConfig("grade", "职位级别", 80);
		columns.add(C6);

		ColumnConfig C1 = new ColumnConfig("resumeNo", "简历编号", 80);
		columns.add(C1);
		ColumnConfig C21 = new ColumnConfig("name", "申请人", 80);
		columns.add(C21);

		ColumnConfig C7 = new ColumnConfig("education", "要求教育", 80);
		columns.add(C7);

		ColumnConfig C22 = new ColumnConfig("bEducation", "具体教育", 80);
		columns.add(C22);

		ColumnConfig C16 = new ColumnConfig("experience", "要求年限", 80);
		columns.add(C16);

		ColumnConfig C23 = new ColumnConfig("bExperience", "具体年限", 80);
		columns.add(C23);

		ColumnConfig C17 = new ColumnConfig("skills", "要求技能", 200);
		columns.add(C17);

		ColumnConfig C25 = new ColumnConfig("bSkills", "具体技能", 200);
		columns.add(C25);

		ColumnConfig C24 = new ColumnConfig("salary", "薪金要求", 80);
		columns.add(C24);

		ColumnConfig C26 = new ColumnConfig("requestDate", "提交日期", 100);
		C26.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C26);

		ColumnConfig C20 = new ColumnConfig("uploadFileName", "上传文件", 200);
		columns.add(C20);
		C20.setRenderer(new GridCellRenderer<ModelData>() {

			public Object render(ModelData model, String property,
					ColumnData config, int rowIndex, int colIndex,
					ListStore<ModelData> store, Grid<ModelData> grid) {
				if (model.get("uploadFile") == null) {
					return "<b><a style=\"color: #385F95; text-decoration: none;\" href=\""
							+ model.get("uploadFileName")
							+ "\" target=\"_blank\">"
							+ model.get("uploadFileName") + "</a>";
				} else {
					return "<b><a style=\"color: #385F95; text-decoration: none;\" href=\""
							+ model.get("uploadFile")
							+ "\" target=\"_blank\">"
							+ model.get("uploadFileName") + "</a>";
				}
			}

		});
		ColumnConfig C31 = new ColumnConfig("situation", "面试情况", 100);
		columns.add(C31);
		ColumnConfig C32 = new ColumnConfig("informationForm", "信息来源", 100);
		columns.add(C32);
		ColumnConfig C33 = new ColumnConfig("reason", "面试不合适原因", 100);
		columns.add(C33);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm, false, false);
		Tools.setResize(grid, 0.97, 0.65);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.setSelectionModel(cbs);
		grid.addPlugin(cbs);
		grid.setLoadMask(true);
		grid.setBorders(false);
		return grid;
	}

	FormPanel form;
	TextField<String> position = new TextField<String>(); // 职位名称
	TextField<String> name = new TextField<String>(); // 申请人
	TextField<String> resumeNo = new TextField<String>(); // 简历编号
	BaseComboBoxX level = new BaseComboBoxX("name", "dictionary",
			"where type='zy'"); // 职位级别
	BaseComboBoxForm<BaseModelData> department = new BaseComboBoxForm<BaseModelData>(
			"id", "name", "systeminfo",
			"where len(id)=(select max(len(id)) from systeminfo)", true); // 职位所属部门
	TextField<String> requestNo = new TextField<String>(); // 职位编号
	DateField start = new DateField(); // 开始提交日期
	DateField end = new DateField(); // 结束提交日期
	
	BaseComboBoxX box = new BaseComboBoxX("name", "dictionary",
	"where type='interview'");  //面试情况
	BaseComboBoxX box1 = new BaseComboBoxX("name", "dictionary",
	"where type='informationFrom'");  //信息来源
	BaseComboBoxX box2 = new BaseComboBoxX("name", "dictionary",
	"where type='reason'");	//面试不适合原因

	private FormPanel createForm() {
		form = new FormPanel();

		start.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		end.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));

		TableLayout tl = new TableLayout(8);

		form.setWidth(913);
		form.setPadding(4);
		form.setBodyBorder(false);
		form.setHeaderVisible(false);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);

		form.add(new Label("职位编号:"), td);
		form.add(requestNo, td);

		form.add(new Label("职位名称:"), td);
		form.add(position, td);

		form.add(new Label("所属部门:"), td);
		form.add(department, td);

		form.add(new Label("职位级别:"), td);
		form.add(level, td);

		form.add(new Label("简历编号:"), td);
		form.add(resumeNo, td);

		form.add(new Label("申请人:"), td);
		form.add(name, td);

		form.add(new Label("申请日期从:"), td);
		form.add(start, td);

		form.add(new Label("到:"), td);
		form.add(end, td);
		
		form.add(new Label("面试情况:"), td);
		form.add(box, td);
		form.add(new Label("信息来源:"), td);
		form.add(box1, td);
		form.add(new Label("不适合原因:"), td);
		form.add(box2, td);

		form.setLayout(tl);

		return form;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.OnClick) {
							String where = "";
							String nameStr = name.getRawValue();
							String positionStr = position.getRawValue();
							String resumeNoStr = resumeNo.getRawValue();
							String levelStr = "";
							String departmentStr = "";
							String situationStr = "";
							String informationStr = "";
							String reasonStr = "";
							String requestNoStr = requestNo.getRawValue();
							String startDate = start.getRawValue();
							String endDate = end.getRawValue();
							
							if (level.getValue() != null) {
								levelStr = level.getValue().get("value");
							}
							if (department.getValue() != null) {
								departmentStr = department.getValue().get(	
										"code");
							}
							if (box.getValue() != null) {
								situationStr = box.getValue().get("value");
							}
							if (box1.getValue() != null) {
								informationStr = box1.getValue().get("value");
							}
							if (box2.getValue() != null) {
								reasonStr = box2.getValue().get("value");
							}
							// 模糊查询和精确查询共用的where语句条件
							if (!levelStr.equals("")) {
								where = where + " and a.grade = '" + levelStr
										+ "'";
							}
							if (!startDate.equals("") || !endDate.equals("")) {
								if (!startDate.equals("")
										|| !endDate.equals("")) {
									where = where
											+ " and c.requestDate between '"
											+ startDate + "' and '" + endDate
											+ "'";
								} else if (!startDate.equals("")) {
									where = where + " and c.requestDate >= '"
											+ startDate;
								} else {
									where = where + " and c.requestDate <= '"
											+ endDate;
								}
							}
							if (!departmentStr.equals("")) {
								where = where + " and a.depCode = '"
										+ departmentStr + "'";
							}
							if (!situationStr.equals("")) {
								where = where + " and c.situation = '" + situationStr + "'";
								interview.setEnabled(false);
							} else {
								interview.setEnabled(true);
								where = where + " and c.situation is null and not exists(select * from hr_positionRequest where situation = '录用' and recruitmentId = c.recruitmentId)";
							}
							if (!informationStr.equals("")) {
								where = where + " and c.informationForm = '" + informationStr + "'";
							}
							if (!reasonStr.equals("")) {
								where = where + " and c.reason = '" + reasonStr + "'";
							}

							// 模糊查询的where语句拼接开始
							if (be.getSource().equals(fuzzy_search)) {
								if (!nameStr.equals("")) {
									where = where + " and b.name like '%25"
											+ nameStr + "%25'";
								}
								if (!positionStr.equals("")) {
									where = where + " and a.position like '%25"
											+ positionStr + "%25'";
								}
								if (!resumeNoStr.equals("")) {
									where = where + " and b.resumeNo like '%25"
											+ resumeNoStr + "%25'";
								}
								if (!requestNoStr.equals("")) {
									where = where
											+ " and a.requestNo like '%25"
											+ requestNoStr + "%25'";
								}
								refreshGrid(where);
								// 精确查询的where语句的拼接开始
							} else if (be.getSource().equals(precise_search)) {
								if (!nameStr.equals("")) {
									where = where + " and b.name = '" + nameStr
											+ "'";
								}
								if (!positionStr.equals("")) {
									where = where + " and a.position = '"
											+ positionStr + "'";
								}
								if (!resumeNoStr.equals("")) {
									where = where + " and b.resumeNo = '"
											+ resumeNoStr + "'";
								}
								if (!requestNoStr.equals("")) {
									where = where + " and a.requestNo = '"
											+ requestNoStr + "'";
								}

								refreshGrid(where);
							} else {
								if (grid.getSelectionModel().getSelectedItems()
										.size() == 0) {
									MessageBox.alert("提示", "申请表为空，请选择申请表，谢谢",
											null);
									return;
								}
								
								Set<Map<String, Object>> list = new HashSet<Map<String, Object>>();
								/*
								 * 循环执行得到选中的复选框的icode，requestNo,并设置面试次数为1，
								 * 这三个参数用map保存，最后装所有的选中申请表放到一个list中。 传到安排面试人员的界面
								 */
								for (BusiObject md : grid.getSelectionModel()
										.getSelectedItems()) {
									Map<String, Object> map = new HashMap<String, Object>();
									int index = grid.getStore().indexOf(md);
									String situation = (String)grid.getValue(index,
									"situation");
									/*
									 * 查询选中的数据中是否有包含为录用的和不录用的记录
									 */
									if (situation != null) {
										if (situation.equals("不录用") || situation.equals("录用")) {
											MessageBox.alert("提示", "你选中的数据行中存在面试情况为‘" + situation + "‘的记录，这些数据不能再进行些操作，请重新选择数据，谢谢", null);
											return;
										}
									}
									long id = (Long) grid.getValue(index,
											"icode");
									String no = (String) grid.getValue(index,
											"requestNo");

									map.put("icode", id);  //申请表编号
									map.put("requestNo", no);  //面试编号
									list.add(map);
								}
								cbs.deselectAll();

								ArrangeInterview audit = new ArrangeInterview();
								audit.setList(list);
								audit.complete();
								BaseTabPanel.getInstance().addTab("安排面试人员",
										audit);
							}
						}
					}
				} finally {
					sync--;
				}

			}

		};
		return defaultlistener;
	}

	/**
	 * @param where
	 *            查询得到的where条件 定义可多次使用的sql，通过传进来的where语句进行查询
	 */
	private void refreshGrid(String where) {
		// 可重用的SQL，用于查询出所有还没安排面试的申请表
		String sql = "select a.requestNo,(select name from systeminfo where id = a.depCode) depCode,a.position,a.grade,a.education,"
				+ "a.experience,a.skills,b.resumeNo,b.name,b.education as bEducation,"
				+ "b.experience as bExperience,b.skills as bSkills,b.salary,"
				+ "b.uploadFile,b.uploadFileName,c.requestDate,c.icode,c.situation,c.informationForm,c.reason"
				+ " from hr_recruitmentRequest a,"
				+ "hr_resumeLibrary b,hr_positionRequest c where a.icode = "
				+ "c.recruitmentId and b.icode = c.resumeLibraryId" + where;
		grid.getStore().getStoreinfo().setSql(sql);
		grid.getStore().reload();
	}
}
